package com.study.mongodb.controller;

import com.mongodb.BasicDBObject;
import com.study.mongodb.dao.PersonDaoImpl;
import com.study.mongodb.dao.SimpleMongoDao;
import com.study.mongodb.entity.Person;
import com.study.mongodb.entity.User;
import com.study.mongodb.utils.MongoDBUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.Clock;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.*;

@RestController
public class TestController {

    @Autowired
    private MongoDBUtil mongoDBUtil;
    @Autowired
    private PersonDaoImpl personDao;

    @GetMapping("/add")
    public String add(){
        Person person = new Person();
        person.setId(1);
        person.setName("wuyu");
        person.setAge(1);
        person.setBirth(LocalDateTime.now());

        mongoDBUtil.save(person);
        return "成功";
    }

    @GetMapping("/get")
    public Person get(String name){
        Person person = (Person)mongoDBUtil.findByName(name, Person.class);
        return person;
    }

    @GetMapping("/batchSave")
    public String batchSave(){
        List<Person> list = new ArrayList<>();
        for(int i = 2; i < 10000; i++){
            Person person = new Person();
            person.setId(i);
            person.setName("wuyu" + i);
            person.setAge(i);
            person.setBirth(LocalDateTime.now().plusMinutes((long)i));
            list.add(person);
        }
        mongoDBUtil.batchSave(list);
        return "成功";
    }

    @GetMapping("/list")
    public List<Person> list(){
        List<Person> byBirth = mongoDBUtil.findByBirth(LocalDateTime.now());
        return byBirth;
    }

    @GetMapping("/add1")
    public String add1(){
        Person person = new Person();
        person.setId(20000);
        person.setName("wuyu");
        person.setAge(20000);
        person.setBirth(LocalDateTime.now());

        personDao.save(person);
        return "成功";
    }

    @GetMapping("/add2")
    public String add2(){
        User u = new User();
        u.setCreateTime(LocalDateTime.now());
        mongoDBUtil.save(u);
        return "保存成功";
    }

    @GetMapping("/list1")
    public List<BasicDBObject> list1(){
        List<BasicDBObject> list = mongoDBUtil.findByBirth(LocalDateTime.of(2022, 3, 3, 9, 30), "agv1");
        return list;
    }

    @GetMapping("/add3")
    public String add3(){
        Map<String, Object> map = new HashMap<>();
        map.put("createTime", LocalDateTime.now());
        map.put("x", 100);
        mongoDBUtil.save1(map);
        return "保存成功";
    }

    @GetMapping("/list2")
    public List<HashMap> list2(){
        List<HashMap> map = mongoDBUtil.findAll(LocalDateTime.now(), "map");
        return map;
    }
}
